package com.fulong.web.webconfig;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new Filter())
                .addPathPatterns("/**") //拦截
                .excludePathPatterns("/" , "/userlogin" , "/register" ,"/getimg","/remote" ); //放行必要的接口
    }

    /*配置数据源启用drudi数据源,绑定配置文件 ，启动监控
     * */
    @ConfigurationProperties("spring.datasource")
    @Bean
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource()  ;
        druidDataSource.setFilters("stat , wall");

        return druidDataSource;
    }


    /*配置阿里云drudi数据源监控，加入容器中，添加拦截路径（可以drudi/*,也可以使用其他的urlMapping）
     * */
    @Bean
    public ServletRegistrationBean statViewServlet()  {

        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(statViewServlet,"/druid/*");
        registrationBean.addInitParameter("loginUsername" , "admin");
        registrationBean.addInitParameter("loginPassword" , "123");
        return  registrationBean;
    }

    @Bean
    public FilterRegistrationBean webStatFilter()  {
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
        //filterRegistrationBean.addUrlPatterns(String.valueOf(Arrays.asList("/**")));
        filterRegistrationBean.addInitParameter("exclusion" , "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean ;
    }
}